var TABLE = require('./db/table');
var util = require('util');

module.exports = function (db) {

    const obj = {};
    obj.update = function (data, where) {
        const dataObj = JSON.parse(data);
        dataObj[TABLE.ballshooter.column.update_at] = db.fn.now();
        if (dataObj[TABLE.ballshooter.column.key]) { // key值存在则不需要多余的where
            where = undefined;
        }
        var insert = db.table(TABLE.ballshooter.tableName).insert(dataObj);
        var update = db.table(TABLE.ballshooter.tableName).update(dataObj).whereRaw(where || '');
        var query = util.format('%s ON CONFLICT (`' + TABLE.ballshooter.column.key + '`) DO UPDATE SET %s',
            insert.toString(),
            update.toString().replace(/^update\s.*\sset\s/i, '')
        );

        return db.raw(query);
    };

    obj.query = function (key, tag) {
        return db.column('*').select().from(TABLE.ballshooter.tableName)
            .where(TABLE.ballshooter.column.key, key)
            .andWhere(TABLE.ballshooter.column.tag, tag);
    };

    return obj;
};
